﻿function Dictionary() {
    this.data = {};
    this._keys = null;
    this._invalidateKeys = false;
}

Dictionary.prototype.invalidate = function () {
    this._invalidateKeys = true;
};

Dictionary.prototype.set = function (key, value) {
    this.data[key] = value;
    this._invalidateKeys = true;
};

Dictionary.prototype.get = function (key) {
    return this.data[key];
};

Dictionary.prototype.getDefault = function (key, _default) {
    if (this.has(key)) {
        return this.data[key];
    } else {
        return _default;
    }
};

Dictionary.prototype.remove = function (key) {
    delete this.data[key];
    this._invalidateKeys = true;
};

Dictionary.prototype.empty = function () {
    var self = this;
    this.forEach(function (id, obj) {
        self.remove(id);
    });
};

Dictionary.prototype.has = function (key) {
    if (this.data.hasOwnProperty(key)) {
        return true;
    } else {
        return false;
    }
}

Dictionary.prototype.size = function () {
    return this.getKeys().length;
};

Dictionary.prototype.forEach = function (cb) {
    for (var key in this.data) {
        if (this.data.hasOwnProperty(key)) {
            if (cb(key, this.data[key]) == false) break;
        }
    }
};

Dictionary.prototype.getKeys = function () {
    if (this._invalidateKeys || this._keys == null) {
        this._keys = Object.keys(this.data);
        this._invalidateKeys = false;
        return this._keys;
    } else {
        return this._keys;
    }
};